/**
 * Build files
 * @author Wangtd
 */
const path = require("path");
const gulp = require('gulp');
const gulpIf = require('gulp-if');
const gulpIgnore = require('gulp-ignore');
const clean = require('gulp-clean');
const cleanCss = require("gulp-clean-css");
const htmlmin = require("gulp-htmlmin");
const rjs = require('gulp-requirejs');
const ngAnnotate = require('gulp-ng-annotate');
const uglifyes = require('uglify-es');
const uglifyComposer = require('gulp-uglify/composer');
const uglify = uglifyComposer(uglifyes, console);
const gulpSequence = require('gulp-sequence');

// clean
gulp.task('cleanall', function () {
    return gulp.src(['temp', 'dist'], {
            read: false, allowEmpty: true
        })
        .pipe(clean({ force: true }));
});

gulp.task('clean', function () {
    return gulp.src('temp', { read: false })
        .pipe(clean({ force: true }));
});

// css
gulp.task('cssmin', function() {
    return gulp.src('app/**/*.css')
        .pipe(gulpIf(function(file) {
            var filename = path.basename(file.path);
            return !/[\.-]min\.css$/.test(filename);
        }, cleanCss({
            rebase: false,
            compatibility: '*',
            keepSpecialComments: '*'
        })))
        .pipe(gulp.dest('temp/dist'));
});

// html
gulp.task('htmlmin', function() {
    return gulp.src('app/**/*.html')
        .pipe(htmlmin({
            collapseWhitespace: true,
            conservativeCollapse: false,
            collapseInlineTagWhitespace: false,
            //preserveLineBreaks: true,
            keepClosingSlash: true,
            ignoreCustomFragments: [],
            minifyCSS: {
                compatibility: '*',
                keepSpecialComments: '*'
            },
            minifyJS: true
        }))
        .pipe(gulp.dest('temp/dist'));
});

// js
gulp.task('jsmin', function() {
    return gulp.src('app/**/*.js')
        // angularjs
        .pipe(gulpIf(function(file) {
            return /(app|config)\.js$/.test(file.path) ||
                /\/app\/views\/.+\.js$/.test(file.path.replace(/\\/g, '/'));
        }, ngAnnotate()))
        // js
        .pipe(gulpIf(function(file) {
            var filename = path.basename(file.path);
            return !/[\.-](min|dist|pack)\.js$/.test(filename);
        }, uglify()))
        .pipe(gulp.dest('temp/dist'));
});

// others
gulp.task('others', function() {
    return gulp.src('app/**/*.*')
        .pipe(gulpIgnore.exclude(function(file) {
            var filename = path.basename(file.path);
            return /\.(css|html|js)$/.test(filename);
        }))
        .pipe(gulp.dest('temp/dist'));
});

// build require.js
gulp.task('buildall', function() {
    return new Promise(function(resolve, reject) {
        try {
            resolve(rjs({
                appDir: 'temp/dist',
                baseUrl: './',
                siteRoot: '../temp/',
                //buildCSS: false,
                mainConfigFile: 'temp/dist/main.js',
                useStrict: false,
                //findNestedDependencies: true,
                removeCombined: true,
                optimize: 'none',//'uglify2',
                skipDirOptimize: true,
                optimizeCss: 'none',//'standard.keepLines',
                name: 'build',
                //include: 'app',
                //insertRequire: ['build'],
                dir: 'temp/app'
            }));
        } catch(e) {
            reject(e);
        }
    });
});

// copy all resources
gulp.task('copyall', function() {
    return gulp.src('temp/app/**/*').pipe(gulp.dest('dist'));
});

gulp.task('default', gulpSequence(
        'cleanall',
        ['cssmin', 'htmlmin', 'jsmin', 'others'],
        'buildall',
        'copyall',
        'clean'
    ));
